package cn.bdqn.sys.service.impl;

import cn.bdqn.model.ConstUtil;
import cn.bdqn.model.EUList;
import cn.bdqn.model.PageBean;
import cn.bdqn.model.R;
import cn.bdqn.service.BaseService;
import cn.bdqn.sys.mapper.UserMapper;
import cn.bdqn.sys.mapper.UserRoleMapper;
import cn.bdqn.sys.model.User;
import cn.bdqn.sys.model.UserExample;
import cn.bdqn.sys.model.UserRoleExample;
import cn.bdqn.sys.service.UserService;
import cn.bdqn.sys.vomapper.RoleVoMapper;
import cn.bdqn.util.ShiroUtils;
import cn.bdqn.util.ValidatorUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Awacky
 * @create 2019-07-27 14:19
 */
@Service
public class UserServiceImpl extends BaseService implements UserService {
    @Resource
    private UserMapper userMapper;
//    @Resource
//    private EnterpriseMapper enterpriseMapper;

    @Override
    public R login(String username, String password, String imageCode) {
//        校验密码和账户不能为空
        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            return R.error("用户名和密码不能为空");
        }
       // String code =(String) this.getSession().getAttribute (ConstUtil.IMAGECODE);
        String code =(String) this.getSession().getAttribute (ConstUtil.IMAGECODE);
        if(StringUtils.isEmpty(imageCode)||!code.equalsIgnoreCase(imageCode)){
            return R.error("验证码错误");
        }

        try {
            Subject subject = ShiroUtils.getSubject ();
            UsernamePasswordToken token = new UsernamePasswordToken (username, password);
            subject.login (token);
        } catch (UnknownAccountException e) {
            return R.error (e.getMessage ());
        } catch (IncorrectCredentialsException e) {
            return R.error ("账号或密码不正确");
        } catch (LockedAccountException e) {
            return R.error ("账号已被锁定,请联系管理员");
        } catch (AuthenticationException e) {
            return R.error ("账户验证失败");
        }

        return R.ok ();
    }

    @Override
    public R update(String oldpassword, String newpassword1, String newpassword2) {
        if (StringUtils.isEmpty(oldpassword)||StringUtils.isEmpty(newpassword1)||StringUtils.isEmpty(newpassword2)){
            return R.error("密码不能为空");
        }else if (!newpassword1.equals(newpassword2)) {
            return R.error("确认密码不一致！！！");

        }
        this.getSession().getAttribute(ConstUtil.USER);
        User user =this.getUser();
        if (!oldpassword.equals(user.getPassword())){
            return R.error("旧密码输入错误");
        }
        user.setPassword(newpassword1);
        try {

            userMapper.updateByPrimaryKey(user);
            return R.ok();
        }catch (Exception e){
            e.printStackTrace();
            return R.error(e.getMessage());
        }

    }

    @Override
    public EUList<User> list(PageBean pageBean, String username, Boolean sex) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andIsdelEqualTo(false);
        criteria.andEidEqualTo(getEid());   //从session来
        criteria.andIsadminEqualTo(false);
        if(!StringUtils.isEmpty(username) || sex != null){
//            criteria.andAccountEqualTo(username);
            criteria.andAccountLike("%"+username+"%");
            criteria.andSexEqualTo(sex);
        }
        PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
        List<User> users = userMapper.selectByExample(example);
        PageInfo<User> info=new PageInfo<>(users);
        return new EUList<>(info.getTotal(),info.getList());
    }

    @Override
    public R save(User user) {
//        try{
        ValidatorUtil.validatorEntity(user);
            if(user.getUid()==null){
                user.setEid(getEid());
                user.setAccount(getEnterprise().getEcode()+"_"+user.getAccount().toUpperCase());
                user.setPassword(ShiroUtils.sha256(ConstUtil.INITIPASSWORD, user.getAccount()));
                userMapper.insertSelective(user);
            }else{
                userMapper.updateByPrimaryKeySelective(user);    //更新时不更新帐号
            }
            return R.ok();
//        }catch (Exception e){
//            e.printStackTrace();
//            return R.error("保存失败");
//        }
    }

    @Override
    public R delete(Integer userid) {
        User user = new User();
        user.setUid(userid);
        user.setIsdel(true);
        try{
            userMapper.updateByPrimaryKeySelective(user);
            return R.ok();
        }catch (Exception e){
            e.printStackTrace();
            return  R.error("删除失败");
        }
    }

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RoleVoMapper roleVoMapper;

    @Transactional
    @Override
    public R setrole(Integer userid, String roleids, String roleNames){
        try{
            UserRoleExample example = new UserRoleExample();
            example.createCriteria().andUserIdEqualTo((long)userid);
            userRoleMapper.deleteByExample(example);
            if(!StringUtils.isEmpty(roleids)){
                roleVoMapper.insertUserRole(roleids, userid, getEid());
            }
            User user = new User();
            user.setUid(userid);
            user.setRoles(roleNames);
            userMapper.updateByPrimaryKeySelective(user);
            return R.ok();
        }catch (Exception e){
            e.printStackTrace();
            return R.error("设置角色错误!");
        }
    }

}
